#include "SalesmanCanvas.h"
#include "parameters.h"
#include <QtDebug>

//Q_DECLARE_METATYPE(QList<int>);


SalesmanCanvas::SalesmanCanvas(QWidget* parent) : QWidget(parent)
{
    TRACE_FUNC
}

SalesmanCanvas::~SalesmanCanvas()
{
    TRACE_FUNC
}

SalesmanData SalesmanCanvas::getData()
{
	return salesmanData;
}

void SalesmanCanvas::setCityPath(QList<int> _cityPath)
{
    if(_cityPath.size() <= salesmanData.size())
    {
        cityPath = _cityPath;
        drawPixmap();
        repaint();
    }
	
}

void SalesmanCanvas::setCityPath(QVariant _cityPath)
{
    //TODO
    QList<QVariant> cPath = _cityPath.toList();
    QList<int> list;
    //list = qVariantValue<QList<int> >(_cityPath);
    //qDebug() << " SalesmanCanvas::setCityPath(QList<QVariant> _cityPath)" << list.size();
    for(int i=0;i<cPath.size();++i)
        list.append(cPath.at(i).toInt());
    setCityPath(list);
}

void SalesmanCanvas::setData(SalesmanData data)
{
    clear();
    salesmanData = data;

    drawPixmap();
}

void SalesmanCanvas::clear()
{
    salesmanData.clear();
    cityPath.clear();

    drawPixmap();
}

void SalesmanCanvas::paintEvent ( QPaintEvent * /*event*/ )
{
    TRACE_FUNC_ENTRY
    QPainter painter;
    painter.begin ( this );

    painter.drawPixmap ( 0, 0, pixmap );

    painter.end ();
    TRACE_FUNC_EXIT
}

void SalesmanCanvas::mousePressEvent ( QMouseEvent *event )
{
    TRACE_FUNC_ENTRY
    qDebug() << "SalesmanCanvas::mousePressEvent " << event->posF();

    salesmanData.addCity(SalesmanCity(QString::number(salesmanData.size()+1), event->posF()));

    drawPixmap();
    TRACE_FUNC_EXIT
}

void SalesmanCanvas::drawPixmap()
{
    TRACE_FUNC_ENTRY
    qDebug() << "SalesmanCanvas::drawPixmap";
    pixmap = QPixmap( this->size() );//create pixmap with size of chart
    pixmap.fill( Qt::transparent );//fill pixmap with trtansparency
    QPainter painterP ( &pixmap );//create painter to draw on pixmap
    QPen pen1(QColor(Qt::blue),3);
    QPen pen2(QColor(Qt::black),2);

    painterP.setPen(pen1);

    painterP.setRenderHint ( QPainter::Antialiasing );

    if(cityPath.size() > salesmanData.size())
        qFatal("wrong path");

    if(cityPath.size() > 0)
    {
        //TODO check if values are correct
        for(int i=0;i<cityPath.size()-1;++i)
        {
            painterP.drawLine(salesmanData.getCity(cityPath.at(i)).getCoord(),salesmanData.getCity(cityPath.at(i+1)).getCoord());
        }
        painterP.drawLine(salesmanData.getCity(cityPath.last()).getCoord(),salesmanData.getCity(cityPath.first()).getCoord());
    }

    painterP.setPen(pen2);
    painterP.setFont(QFont("Arial",16));

    for(int i=0;i<salesmanData.size();++i)
    {
        painterP.drawEllipse(salesmanData.getCity(i).getCoord(),3,3);
        //painterP.drawPoint(salesmanData.getCity(i).getCoord());
        painterP.drawText(salesmanData.getCity(i).getCoord(), salesmanData.getCity(i).getName());
    }



    update ();
    TRACE_FUNC_EXIT
}
